package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {

   @Autowired
   private CheckItemMapper checkItemMapper;

   @Override
   public void add(CheckItem checkItem) {
      //调用checkItemMapper的add方法
      checkItemMapper.add(checkItem);
   }

   @Override
   public PageResult findPage(QueryPageBean pageBean) {
      //1.使用分页助手进行分页
      PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());

      //2.调用checkItemMapper的findByCondition方法
      String queryString = pageBean.getQueryString();
      Page<CheckItem> page = checkItemMapper.findByCondition(queryString);

      //3.封装放回对象
      return new PageResult(page.getTotal(), page.getResult());

   }

   @Override
   public void delete(Integer id) throws RuntimeException {
      //1.判断是是否存在于检查组的关联
      Integer count = checkItemMapper.findGroupRelation(id);
      if (count > 0) {
         //存在关联,不允许删除
         throw new RuntimeException();//手动抛出异常,让service层捕获
      }

      //2.未关联,进行删除
      checkItemMapper.deleteById(id);
   }

   @Override
   public void update(CheckItem checkItem) throws RuntimeException {
      //1.判断检查项是否存在
      CheckItem checkItem1 = checkItemMapper.findById(checkItem.getId());
      if (checkItem1 == null) {//不存在
         throw new RuntimeException();

      } else {
         //2.存在,进行修改
         checkItemMapper.update(checkItem);
      }

   }

   @Override
   public CheckItem findById(Integer id) {
      CheckItem checkItem = checkItemMapper.findById(id);
      return checkItem;
   }

   @Override
   public List<CheckItem> findAll() {
      List<CheckItem> checkItemList = checkItemMapper.findAll();
      return checkItemList;
   }


}
